<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="view-account-top-logo">
          <img :src="websiteConfig.loginImage" alt="" />
        </div>
        <div class="view-account-top-desc">{{ stepDetail.desc[stepDetail.step] }}</div>
      </div>
      <div class="view-account-form">
        <!-- 验证用户名 -->
        <n-form
          v-if="!stepDetail.step"
          ref="formRef"
          label-placement="left"
          size="large"
          :model="checkUsernameForm"
        >
          <n-form-item>
            <n-input v-model:value="checkUsernameForm.username" placeholder="请输入用户名">
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <PersonOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item class="default-color">
            <div style="width: 100%" class="flex justify-between">
              <div class="flex-initial order-1">
                <a href="javascript:" @click="router.replace('/')">回到首页</a>
              </div>

              <div class="flex-initial order-last">
                <a href="javascript:" @click="router.replace('/login')">回到登录页</a>
              </div>
            </div>
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSubmit" size="large" :loading="loading" block>
              找回密码
            </n-button>
          </n-form-item>
        </n-form>

        <!-- 重置密码 -->
        <n-form
          v-if="stepDetail.step"
          ref="formRef"
          label-placement="left"
          size="large"
          :model="resetPwdForm"
          :rules="rules"
        >
          <n-form-item path="password">
            <n-input
              v-model:value="resetPwdForm.password"
              type="password"
              showPasswordOn="click"
              placeholder="请输入密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="checkPassword">
            <n-input
              v-model:value="resetPwdForm.checkPassword"
              type="password"
              showPasswordOn="click"
              placeholder="请再次输入密码"
              @keyup.enter="handleSubmit"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item class="default-color">
            <div style="width: 100%" class="flex justify-between">
              <div class="flex-initial order-1">
                <a href="javascript:" @click="router.replace('/')">回到首页</a>
              </div>

              <div class="flex-initial order-last">
                <a href="javascript:" @click="router.replace('/login')">回到登录页</a>
              </div>
            </div>
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSubmit" size="large" :loading="loading" block>
              找回密码
            </n-button>
          </n-form-item>
        </n-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { useMessage, FormItemRule } from 'naive-ui';
import { websiteConfig } from '@/config/website.config';
import { setInfo } from "@/views/result/ResultStorage";
import { PersonOutline, LockClosedOutline } from '@vicons/ionicons5';
import { checkUsername, resetPwdByEmail } from "@/api/authority/user";
import {ResultEnum} from "@/enums/httpEnum";

const formRef = ref();
const message = useMessage();
const router = useRouter();
const route = useRoute();

const userStore = useUserStore();

// 密码校验规则
const validatePasswordStartWith = (rule: FormItemRule, value: string): boolean => {
  return (
    !!resetPwdForm.password &&
    resetPwdForm.password.startsWith(value) &&
    resetPwdForm.password.length >= value.length
  );
};
function validatePasswordSame (rule: FormItemRule, value: string): boolean {
  return value === resetPwdForm.password;
}
const rules = {
  password: { required: true, message: '请输入密码', trigger: 'blur' },
  checkPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur'],
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input',
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input'],
    }
  ],
};

// 0: 验证用户名 1: 重置密码
const stepDetail = reactive({
  step: 0,
  title: ['验证用户名', '重置密码'],
  desc: ['请通过输入本系统用户名重置你的密码', '请设置您的新密码']
})
const loading = ref(false);
const checkUsernameForm = reactive({
  username: ''
})
const resetPwdForm = reactive({
  email: '',
  password: '',
  checkPassword: '',
  code: ''
})

onMounted(() => {
  const params = route.params
  if (params?.email && params?.code) {
    // @ts-ignore
    resetPwdForm.email = params.email
    // @ts-ignore
    resetPwdForm.code = params.code
    document.title = '重置密码'
    stepDetail.step = 1
  } else {
    document.title = '找回密码'
    stepDetail.step = 0
  }
})

const handleSubmit = async () => {
  loading.value = true;
  try {
    // 验证用户名
    if (stepDetail.step === 0) {
      if (!checkUsernameForm.username) {
        return message.error('请输入用户名')
      }
      const { code, message: msg, data } = await checkUsername(checkUsernameForm.username)
      if (ResultEnum.SUCCESS === code) {
        setInfo({
          status: 'success',
          title: '操作成功',
          description: `账户验证成功`,
          content: `我们已经向您的邮箱 ${data.email} 发送了一封邮件，请注意查收`,
          createTime: Date.now()
        })
      } else {
        return message.error(msg)
      }
      await router.push('/result')
    }
    // 重置密码
    if (stepDetail.step === 1) {
      const { code, message: msg } = await resetPwdByEmail(resetPwdForm)
      if (ResultEnum.SUCCESS === code) {
        setInfo({
          status: 'success',
          title: '操作成功',
          description: `密码重置成功`,
          content: `请及时记录好您的登录密码, 以免忘记`,
          createTime: Date.now()
        })
      } else {
        return message.error(msg)
      }
      await router.push('/result')
    }
  } finally {
    loading.value = false;
  }
}

</script>

<style lang="less" scoped>
.view-account {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;

  &-container {
    flex: 1;
    padding: 32px 12px;
    max-width: 384px;
    min-width: 320px;
    margin: 0 auto;
  }

  &-top {
    padding: 32px 0;
    text-align: center;

    &-desc {
      font-size: 14px;
      color: #808695;
    }
  }

  &-other {
    width: 100%;
  }

  .default-color {
    color: #515a6e;

    .ant-checkbox-wrapper {
      color: #515a6e;
    }
  }
}

@media (min-width: 768px) {
  .view-account {
    background-image: url('../../assets/images/login.svg');
    background-repeat: no-repeat;
    background-position: 50%;
    background-size: 100%;
  }

  .page-account-container {
    padding: 32px 0 24px 0;
  }
}
</style>
